package xiaojian.toolkit.netty.handler.codec.http.transformer;

import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.bean.tlv.decode.TLVDecoderOfBean;
import xiaojian.toolkit.util.ByteUtils;

/**
 * @author hp
 */
public class TLVTransformer implements HttpRequestTransformer {

	private static final Logger logger = LoggerFactory
			.getLogger(TLVTransformer.class);

	private TLVDecoderOfBean decoder;
	private Class<?> targetType;
	private int dumpBytes = 1024;

	/**
	 * @return the targetType
	 */
	public Class<?> getTargetType() {
		return targetType;
	}

	/**
	 * @param targetType
	 *            the targetType to set
	 */
	public void setTargetType(Class<?> targetType) {
		this.targetType = targetType;
	}

	/**
	 * @return the decoder
	 */
	public TLVDecoderOfBean getDecoder() {
		return decoder;
	}

	/**
	 * @param decoder
	 *            the decoder to set
	 */
	public void setDecoder(TLVDecoderOfBean decoder) {
		this.decoder = decoder;
	}

	@Override
	public Object transform(FullHttpRequest request) {

		int contentLength = 0;

		try {
			String value = request.headers().get(
					HttpHeaders.Names.CONTENT_LENGTH);
			contentLength = Integer.parseInt(value);
		} catch (Exception e) {
			logger.error("transform", e);
		}

		if (contentLength > 0) {
			byte[] bytes = new byte[contentLength];
			request.content().readBytes(bytes);

			if (logger.isTraceEnabled()) {
				logger.trace("decode TLV's raw bytes -->");
				logger.trace(ByteUtils.bytesAsTLVHexString(bytes, dumpBytes));
			}
			Object bean = decoder.decode(
					contentLength,
					bytes,
					decoder.getDecodeContextFactory().createDecodeContext(
							targetType, null));
			return bean;
		}

		return null;
	}

	/**
	 * @return the dumpBytes
	 */
	public int getDumpBytes() {
		return dumpBytes;
	}

	/**
	 * @param dumpBytes
	 *            the dumpBytes to set
	 */
	public void setDumpBytes(int dumpBytes) {
		this.dumpBytes = dumpBytes;
	}

}
